package handlers

import (
	"restaurant-system/config"
	"restaurant-system/internal/models"

	"github.com/gin-gonic/gin"
)

// 创建配送地址请求
type CreateDeliveryAddressRequest struct {
	Name      string  `json:"name" binding:"required"`
	Phone     string  `json:"phone" binding:"required"`
	Address   string  `json:"address" binding:"required"`
	Latitude  float64 `json:"latitude" binding:"required"`
	Longitude float64 `json:"longitude" binding:"required"`
	Tag       string  `json:"tag"`
	IsDefault bool    `json:"is_default"`
}

// 创建配送地址
func CreateDeliveryAddress(c *gin.Context) {
	userID, _ := c.Get("userID")
	var req CreateDeliveryAddressRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	tx := config.DB.Begin()

	// 如果设置为默认地址，先取消其他默认地址
	if req.IsDefault {
		if err := tx.Model(&models.DeliveryAddress{}).
			Where("user_id = ? AND is_default = ?", userID, true).
			Update("is_default", false).Error; err != nil {
			tx.Rollback()
			c.JSON(500, gin.H{"error": "更新默认地址失败"})
			return
		}
	}

	address := models.DeliveryAddress{
		UserID:    userID.(uint),
		Name:      req.Name,
		Phone:     req.Phone,
		Address:   req.Address,
		Latitude:  req.Latitude,
		Longitude: req.Longitude,
		Tag:       req.Tag,
		IsDefault: req.IsDefault,
	}

	if err := tx.Create(&address).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "创建配送地址失败"})
		return
	}

	tx.Commit()
	c.JSON(200, gin.H{"message": "创建配送地址成功", "address": address})
}

// 获取用户配送地址列表
func GetDeliveryAddresses(c *gin.Context) {
	userID, _ := c.Get("userID")
	var addresses []models.DeliveryAddress

	if err := config.DB.Where("user_id = ?", userID).Find(&addresses).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取配送地址列表失败"})
		return
	}

	c.JSON(200, gin.H{"addresses": addresses})
}

// 设置默认地址
func SetDefaultAddress(c *gin.Context) {
	userID, _ := c.Get("userID")
	addressID := c.Param("id")

	tx := config.DB.Begin()

	// 取消其他默认地址
	if err := tx.Model(&models.DeliveryAddress{}).
		Where("user_id = ? AND is_default = ?", userID, true).
		Update("is_default", false).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "更新默认地址失败"})
		return
	}

	// 设置新的默认地址
	if err := tx.Model(&models.DeliveryAddress{}).
		Where("id = ? AND user_id = ?", addressID, userID).
		Update("is_default", true).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "设置默认地址失败"})
		return
	}

	tx.Commit()
	c.JSON(200, gin.H{"message": "设置默认地址成功"})
}
